/*
 * pps_bom
 */
package com.pitop.assembly.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.baidu.fsg.uid.UidGenerator;
import com.pitop.assembly.dao.AssemblyCategoryDAO;
import com.pitop.assembly.entity.AssemblyCategory;
import com.pitop.assembly.entity.AssemblyCategoryState;
import com.pitop.core.base.BaseDAO;
import com.pitop.core.base.BaseSVImpl;
import com.pitop.core.entity.Page;
import com.pitop.core.enums.YNEnum;
import com.pitop.core.exceptions.AssemblyCategoryException;
import com.pitop.core.exceptions.BaseException;
import com.pitop.core.tools.StringTools;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.map.HashedMap;
import org.apache.ibatis.session.RowBounds;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service("assemblyCategorySV")
@Slf4j
public class AssemblyCategorySVImpl extends BaseSVImpl<AssemblyCategory, Long> implements AssemblyCategorySV {

    @Autowired
    private AssemblyCategoryDAO assemblyCategoryDAO;

    @Resource
    private UidGenerator uidGenerator;

    @Override
    protected BaseDAO getBaseDAO() {
        return assemblyCategoryDAO;
    }

    /**
     * 保存account对象
     * 1. 判断创建的分类是否已经存在
     * 2. 上级分类编码是否为空，为空设置本级级别为1；不为空，取上级级别加1
     * 3. 数据持久化
     *
     * @param entity 实体
     */
    @Override
    public void save(AssemblyCategory entity) throws BaseException {
        //1. 判断创建的分类是否已经存在
        Map<String, Object> params = new HashMap<>();
        params.put("name", entity.getName());
        AssemblyCategory assemblyCategoryFlag = assemblyCategoryDAO.load(params);
        if (assemblyCategoryFlag != null) {
            throw new AssemblyCategoryException(BaseException.BaseExceptionEnum.Exists);
        }
        //2. 上级分类编码是否为空，为空设置本级级别为1；不为空，取上级级别加1
        if (StringTools.isEmpty(entity.getPreCode())) {
            entity.setLevel(1);
        } else {
            AssemblyCategory assemblyCategory = assemblyCategoryDAO.loadByCode(entity.getPreCode());
            if (assemblyCategory == null) {
                throw new AssemblyCategoryException(BaseException.BaseExceptionEnum.Illegal_Param);
            }
            entity.setLevel(assemblyCategory.getLevel() + 1);
        }
        //3. 数据持久化
        entity.setCode(String.valueOf(uidGenerator.getUID()));
        entity.setState(AssemblyCategoryState.Enable.name());
        super.save(entity);
    }

    /**
     * 修改组件类型
     *
     * @return AssemblyCategory
     */
    @Override
    public void modify(AssemblyCategory assemblyCategory) {
        //1. 判断创建的分类是否已经存在
        AssemblyCategory entity = assemblyCategoryDAO.loadByCode(assemblyCategory.getCode());
        if (entity == null) {
            throw new AssemblyCategoryException(BaseException.BaseExceptionEnum.Result_Not_Exist);
        }
        Map<String, Object> params = new HashMap<>();
        params.put("name", entity.getName());
        AssemblyCategory assemblyCategoryFlag = assemblyCategoryDAO.load(params);
        if (assemblyCategoryFlag == null && !entity.getCode().equals(assemblyCategoryFlag.getCode())) {
            throw new AssemblyCategoryException(BaseException.BaseExceptionEnum.Assembly_Category_Name_Exist);
        }
        //2. 上级分类编码是否为空，为空设置本级级别为1；不为空，取上级级别加1
        if (StringTools.isEmpty(entity.getPreCode())) {
            assemblyCategory.setLevel(1);
        } else {
            AssemblyCategory fatherCategory = assemblyCategoryDAO.loadByCode(entity.getPreCode());
            if (fatherCategory == null) {
                throw new AssemblyCategoryException(BaseException.BaseExceptionEnum.Illegal_Param);
            }
            assemblyCategory.setLevel(fatherCategory.getLevel() + 1);
        }
        //3. 数据持久化
        super.modify(assemblyCategory);
    }

    /**
     * 加载一个对象AssemblyCategory
     *
     * @param id
     * @param code 编码
     * @return AssemblyCategory
     */
    @Override
    public AssemblyCategory load(Long id, String code) {
        if (id == null && code == null) {
            throw new AssemblyCategoryException(BaseException.BaseExceptionEnum.Illegal_Param);
        }

        Map<String, Object> param = new HashMap<>();
        param.put("id", id);
        param.put("code", code);
        return assemblyCategoryDAO.load(param);
    }

    /**
     * 加载一个对象AssemblyCategory,(将查询关联数据)
     *
     * @param id
     * @param code 编码
     * @return AssemblyCategory
     */
    @Override
    public AssemblyCategory get(Long id, String code) {
        if (id == null && code == null) {
            throw new AssemblyCategoryException(BaseException.BaseExceptionEnum.Illegal_Param);
        }

        Map<String, Object> param = new HashMap<>();
        param.put("id", id);
        param.put("code", code);
        return assemblyCategoryDAO.getDetail(id, code);
    }

    /**
     * 加载一个对象AssemblyCategory 通过id
     *
     * @param id
     * @return AssemblyCategory
     */
    @Override
    public AssemblyCategory loadById(Long id) {
        if (id == null) {
            throw new AssemblyCategoryException(BaseException.BaseExceptionEnum.Illegal_Param);
        }
        return assemblyCategoryDAO.loadById(id);
    }

    /**
     * 加载一个对象AssemblyCategory 通过code
     *
     * @param code 编码
     * @return AssemblyCategory
     */
    @Override
    public AssemblyCategory loadByCode(String code) {
        if (code == null) {
            throw new AssemblyCategoryException(BaseException.BaseExceptionEnum.Illegal_Param);
        }
        return assemblyCategoryDAO.loadByCode(code);
    }

    /**
     * 加载一个对象AssemblyCategory 通过name
     *
     * @param name 编码
     * @return AssemblyCategory
     */
    @Override
    public AssemblyCategory loadByName(String name) {
        Map<String, Object> params = new HashedMap();
        params.put("name", name);
        return assemblyCategoryDAO.load(params);
    }

    /**
     * 加载一个对象AssemblyCategory 通过id,(将查询关联数据)
     *
     * @param id
     * @return AssemblyCategory
     */
    @Override
    public AssemblyCategory getById(Long id) {
        if (id == null) {
            throw new AssemblyCategoryException(BaseException.BaseExceptionEnum.Illegal_Param);
        }
        return assemblyCategoryDAO.getById(id);
    }

    /**
     * 加载一个对象AssemblyCategory 通过code,(将查询关联数据)
     *
     * @param code 编码
     * @return AssemblyCategory
     */
    @Override
    public AssemblyCategory getByCode(String code) {
        if (code == null) {
            throw new AssemblyCategoryException(BaseException.BaseExceptionEnum.Illegal_Param);
        }
        return assemblyCategoryDAO.getByCode(code);
    }

    /**
     * 根据主键id,oldStates 共同更新 AssemblyCategory 的状态到newState状态
     *
     * @param id
     * @param newState  新状态
     * @param oldStates 旧状态集合
     */
    @Override
    public void updateStateById(Long id, AssemblyCategoryState newState, AssemblyCategoryState... oldStates) {
        if (id == null) {
            throw new AssemblyCategoryException(BaseException.BaseExceptionEnum.Illegal_Param);
        }
        if (newState == null) {
            throw new AssemblyCategoryException(BaseException.BaseExceptionEnum.Illegal_Param);
        }
        if (oldStates == null) {
            throw new AssemblyCategoryException(BaseException.BaseExceptionEnum.Illegal_Param);
        }
        String[] states = new String[oldStates.length];
        for (int i = 0; i < oldStates.length; i++) {
            states[i] = oldStates[i].name();
        }
        assemblyCategoryDAO.updateStateById(id, new Date(), newState.name(), states);
    }

    /**
     * 根据主键code,oldStates 共同更新 AssemblyCategory 的状态到newState状态
     *
     * @param code      编码
     * @param newState  新状态
     * @param oldStates 旧状态集合
     */
    @Override
    public void updateStateByCode(String code, AssemblyCategoryState newState, AssemblyCategoryState... oldStates) {
        if (code == null) {
            throw new AssemblyCategoryException(BaseException.BaseExceptionEnum.Illegal_Param);
        }
        if (newState == null) {
            throw new AssemblyCategoryException(BaseException.BaseExceptionEnum.Illegal_Param);
        }
        if (oldStates == null) {
            throw new AssemblyCategoryException(BaseException.BaseExceptionEnum.Illegal_Param);
        }
        String[] states = new String[oldStates.length];
        for (int i = 0; i < oldStates.length; i++) {
            states[i] = oldStates[i].name();
        }
        assemblyCategoryDAO.updateStateByCode(code, new Date(), newState.name(), states);
    }

    /**
     * 根据主键id 更新 AssemblyCategory 的状态到另一个状态
     *
     * @param id
     * @param state 状态
     */
    @Override
    public void updateById(Long id, AssemblyCategoryState state) {
        if (id == null) {
            throw new AssemblyCategoryException(BaseException.BaseExceptionEnum.Illegal_Param);
        }
        assemblyCategoryDAO.updateById(id, state.name(), new Date());
    }

    /**
     * 根据主键code 更新 AssemblyCategory 的状态到另一个状态
     *
     * @param code  编码
     * @param state 状态
     */
    @Override
    public void updateByCode(String code, AssemblyCategoryState state) {
        if (code == null) {
            throw new AssemblyCategoryException(BaseException.BaseExceptionEnum.Illegal_Param);
        }
        assemblyCategoryDAO.updateByCode(code, state.name(), new Date());
    }


    /**
     * 删除对象AssemblyCategory
     *
     * @param id * @param code 编码
     * @return AssemblyCategory
     */
    @Override
    public void delete(Long id, String code) {
        if (id == null && code == null) {
            throw new AssemblyCategoryException(BaseException.BaseExceptionEnum.Illegal_Param);
        }
        Map<String, Object> param = new HashMap<>();
        param.put("id", id);
        param.put("code", code);
        assemblyCategoryDAO.delete(param);
    }


    /**
     * 查询AssemblyCategory分页
     *
     * @param assemblyCategory 对象
     * @param offset           查询开始行
     * @param limit            查询行数
     * @return List<AssemblyCategory>
     */
    @Override
    public List<AssemblyCategory> list(AssemblyCategory assemblyCategory, String isShowAll, int offset, int limit) {
        if (offset < 0) {
            offset = 0;
        }

        if (limit < 0) {
            limit = Page.limit;
        }
        Map<String, Object> map = null;
        if (assemblyCategory != null) {
            map = JSON.parseObject(JSON.toJSONString(assemblyCategory, SerializerFeature.WriteDateUseDateFormat));
        } else {
            map = new HashMap<>();
        }
        if (YNEnum.N == YNEnum.getYN(isShowAll) && StringTools.isEmpty(assemblyCategory.getPreCode())) {
            map.put("level", 1);
        }
        List<AssemblyCategory> assemblyCategories = assemblyCategoryDAO.list(map, new RowBounds(offset, limit));
        String code;
        for (AssemblyCategory assemblyCategoryFlag : assemblyCategories) {
            if(StringTools.isNotEmpty(assemblyCategoryFlag.getPreCode())) {
                assemblyCategoryFlag.setPreName(assemblyCategoryDAO.loadByCode(assemblyCategoryFlag.getPreCode()).getName());
            }
            code = assemblyCategoryFlag.getCode();
            int count = assemblyCategoryDAO.countByPreCode(code);
            assemblyCategoryFlag.setHasChild(count > 0 ? true : false);
        }
        return assemblyCategories;
    }

    @Override
    public int count(AssemblyCategory assemblyCategory) {
        Map<String, Object> map = null;
        if (assemblyCategory != null) {
            map = JSON.parseObject(JSON.toJSONString(assemblyCategory, SerializerFeature.WriteDateUseDateFormat));
        } else {
            map = new HashMap<>();
        }
        if (StringTools.isEmpty(assemblyCategory.getPreCode())) {
            map.put("level", 1);
        }
        return assemblyCategoryDAO.count(map);
    }

    /**
     * 查询AssemblyCategory分页
     *
     * @param id     * @param code  编码
     * @param offset 查询开始行
     * @param limit  查询行数
     * @return List<AssemblyCategory>
     */
    @Override
    public List<AssemblyCategory> list(Long id, String code, int offset, int limit) {
        if (offset < 0) {
            offset = 0;
        }

        if (limit < 0) {
            limit = Page.limit;
        }
        Map<String, Object> param = new HashMap<>();
        param.put("id", id);
        param.put("code", code);
        return assemblyCategoryDAO.list(param, new RowBounds(offset, limit));
    }

    @Override
    public int count(Long id, String code) {
        Map<String, Object> param = new HashMap<>();
        param.put("id", id);
        param.put("code", code);
        return assemblyCategoryDAO.count(param);
    }

}
